
import sys 
import os
from PIL import Image


def detectEdge(img, w, h):
    
    left, upper, right, lower = w,h,0,0
    pixels = img.load()
    threshold = 10
    for x in range(0,w):
        for y in xrange(0,h):
            pix = pixels[x,y]
            if (pix[0]<(254-threshold) or pix[1]<(254-threshold) or pix[2]<(254-threshold)) and pix[3]>0:
                left, upper, right, lower = min(x,left),min(y,upper),max(x,right),max(y,lower)
    return (left, upper, right, lower)
	

if __name__ == '__main__': 
    dirList=os.listdir(sys.argv[1])
    for fname in dirList:
        if fname.endswith(sys.argv[3]):
            img = Image.open(os.path.join(sys.argv[1],fname))
            width, height = img.size 
            box = detectEdge(img,width,height)
            print fname, box
            img2 = img.crop(box)
            # img2 = img2.resize((width, height), Image.ANTIALIAS)
            img2 = img2.resize(((box[2]-box[0]), (box[3]-box[1])), Image.ANTIALIAS)
            img2.save(os.path.join(sys.argv[2],fname))
